package com.iceland.server.service;

import com.iceland.common.rpc.RemoteService;
import com.iceland.common.rpc.RpcMessageManager;
import com.iceland.common.rpc.RpcMessageManagerHolder;
import com.iceland.common.service.server.RemoteServerService;
import com.iceland.common.util.ChannelContext;
import com.iceland.server.server.proxy.ProxyServer;
import com.iceland.server.server.proxy.ProxyServerManager;
import com.iceland.server.util.ServerChannelContext;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MarkerFactory;

@Slf4j
@RemoteService(path = "server")
public class RemoteServerServiceImpl implements RemoteServerService {
    ProxyServerManager proxyServerManager=ProxyServerManager.getSingleInstance();

    /**
     * 启动代理服务器
     * @param port
     */
    @Override
    public int startProxyServer(Integer port) throws Exception {
        RpcMessageManager rpcMessageManager = RpcMessageManagerHolder.getRpcMessageManager();
        ServerChannelContext channelContext = (ServerChannelContext)rpcMessageManager.getChannelContext();

        try {
            port = proxyServerManager.addServer(port);
        } catch (Exception e) {
            throw e;
        }
        ProxyServer server = proxyServerManager.getServer(port);
        channelContext.setProxyServer(server);
        server.setRpcMessageManager(rpcMessageManager);

        log.info(MarkerFactory.getMarker(this.getClass().getTypeName()),"成功启动代理服务器，port：{},调用者为:{}",port,rpcMessageManager.getChannel().remoteAddress());

        return port;
    }
    @Override
    public void closeProxyServer(Integer port) {
        proxyServerManager.closeServer(port);
        RpcMessageManager rpcMessageManager = RpcMessageManagerHolder.getRpcMessageManager();
        ChannelContext channelContext = rpcMessageManager.getChannelContext();

    }
}
